package com.controller.lib.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.ui.PlayerControlView;
import com.controller.lib.R;
import com.controller.lib.utils.FileUtils;
import com.google.android.exoplayer2.ui.PlayerView;
import java.io.File;
import timber.log.Timber;

import static com.google.android.exoplayer2.ui.AspectRatioFrameLayout.RESIZE_MODE_FILL;

/**
 * @author : GeRui
 * date   : 2025/6/25 13:32
 * desc   :播放视频
 * version: 1.0
 */
public class PlayerViewActivity extends AppCompatActivity {

  private PlayerView playerView;
  // 创建简单播放器
  private ExoPlayer player;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 1. 创建根布局（LinearLayout）
    LinearLayout rootLayout = new LinearLayout(this);
    rootLayout.setOrientation(LinearLayout.VERTICAL);
    rootLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));
    rootLayout.setLayoutParams(new LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT
    ));
    Timber.d("rlPlayerView_"+rootLayout);
    getPlayerView();
    Timber.d("playerView"+playerView);
    rootLayout.addView(playerView);
    setContentView(rootLayout);
    initializePlayer();
    String videoUrl = getVideoUrl(getIntent());
    Timber.i("Video URL: %s", videoUrl);
    if (!TextUtils.isEmpty(videoUrl)) {
      setVideoMediaItem(videoUrl);
      player.play();
    }
  }

  @Override protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String videoUrl = getVideoUrl(intent);
    Timber.i("Video URL: %s", videoUrl);
    if (!TextUtils.isEmpty(videoUrl)) {
      setVideoMediaItem(videoUrl);
    }
  }

  private void initializePlayer() {
    player = new ExoPlayer.Builder(this).build();
    playerView.setPlayer(player);
    // 设置媒体项并播放
    player.addListener(new Player.Listener() {
      @Override
      public void onPlayerError(@NonNull PlaybackException error) {
        // 处理错误
        Timber.e("ExoPlayer Error: %s", error.getMessage());
      }
    });
  }

  /**
   * 替换视频，有新的视频URL时调用此方法。
   */
  private void setVideoMediaItem(String videoUrl) {
    if (TextUtils.isEmpty(videoUrl)) {
      Timber.e("Video URL is empty or null.");
      return;
    }
    MediaItem newMediaItem;
    if(FileUtils.Companion.isValidPathFormat(videoUrl)){
      newMediaItem = MediaItem.fromUri(Uri.fromFile(new File(videoUrl)));
      Timber.d("Creating MediaItem from file: %s", videoUrl);
    }else{
      newMediaItem = MediaItem.fromUri(videoUrl);
      Timber.d("Creating MediaItem from URL: %s", videoUrl);
    }

    // 替换视频（保留当前播放状态）
    player.setMediaItem(newMediaItem, false);
    player.prepare();
    // 或者使用平滑切换（需要提前准备多个视频）
    // player.seekToDefaultPosition(1); // 切换到下一个视频
  }

  private  String getVideoUrl(Intent intent) {
    if (intent != null) {
      return intent.getStringExtra("video_url");
    }
    return "";
  }
  @Override protected void onStart() {
    super.onStart();
    playerView.onResume();
  }

  @Override protected void onResume() {
    super.onResume();
    playerView.onResume();
  }

  @Override protected void onPause() {
    super.onPause();
    playerView.onPause();
  }

  @Override protected void onStop() {
    super.onStop();
    playerView.onPause();
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    player.release();
  }


  private PlayerView getPlayerView() {
    playerView=new PlayerView(this);
    playerView.setShowBuffering(PlayerView.SHOW_BUFFERING_WHEN_PLAYING);
    playerView.setUseController(true);
    playerView.setShowShuffleButton(true);
    playerView.setResizeMode(RESIZE_MODE_FILL);
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT
    );
    params.gravity = Gravity.CENTER;
    playerView.setLayoutParams(params);
    return playerView;
  }
}